//
//  LoginViewController.m
//  YouinRTCDemo
//
//  Created by 潘欣 on 2023/6/21.
//

#import "LoginViewController.h"
#import "LiveRoomViewController.h"
#import "WebViewController.h"
#import "AFNetworking.h"
#import "LiveListViewController.h"
#import "Reachability.h"
@interface LoginViewController ()
@property (nonatomic,strong)UITextField *nameField;
@property (nonatomic,strong)UITextField *pswField;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    img.image = [UIImage imageNamed:@"login_bg"];
    img.userInteractionEnabled = YES;
    [self.view addSubview:img];
    
    float viewWidth = (SCREEN_WIDTH-40);
    float ViewY = (SCREEN_HEIGHT-viewWidth-30)/2;
    
    //    logo 936 × 470 = scr*x
    float leftSpace = SCREEN_WIDTH/5;
    float logoHight = (leftSpace*3)*470/936;
    UIImageView *logoImg = [[UIImageView alloc] initWithFrame:CGRectMake(leftSpace, ViewY-logoHight-40, SCREEN_WIDTH-(leftSpace*2), logoHight)];
    logoImg.image = [UIImage imageNamed:@"inlogo"];
    [self.view addSubview:logoImg];

    
   
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(20, ViewY+30, viewWidth, viewWidth-30)];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.layer.cornerRadius = 15;
    bgView.layer.shadowColor = [UIColor grayColor].CGColor;
        // 阴影偏移，默认(0, -3)
    bgView.layer.shadowOffset = CGSizeMake(0,0);
        // 阴影透明度，默认0
    bgView.layer.shadowOpacity = 0.5;
        // 阴影半径，默认3
    bgView.layer.shadowRadius = 3;
 
    [self.view addSubview:bgView];
    
    
    
    //获取已保存的用户信息
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *dict = [defaults dictionaryForKey:@"userInfo"];

    
    
    
    self.nameField = [[UITextField alloc] initWithFrame:CGRectMake(50, 30, bgView.frame.size.width-100, 35)];
    NSAttributedString *str = [[NSAttributedString alloc] initWithString:@"请输入登录账号" attributes:@{ NSForegroundColorAttributeName: [UIColor grayColor] }];
    self.nameField.attributedPlaceholder = str;
    self.nameField.font = [UIFont systemFontOfSize:15];
    // 创建一个UIImageView来显示图标
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 18, 18)];
    UIImageView *iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(-6, 0, 15, 15)];
    iconImageView.image = [UIImage imageNamed:@"name.png"];
    [view addSubview:iconImageView];
    self.nameField.leftView = view;
    self.nameField.leftViewMode = UITextFieldViewModeAlways;
    [bgView addSubview:self.nameField];
    
    UILabel *line1 = [[UILabel alloc] initWithFrame:CGRectMake(self.nameField.frame.origin.x, self.nameField.frame.origin.y+self.nameField.frame.size.height+10, self.nameField.frame.size.width, 1)];
    line1.backgroundColor = [UIColor lightGrayColor];
    line1.alpha = 0.1;
    [bgView addSubview:line1];
    
    
    self.pswField = [[UITextField alloc] initWithFrame:CGRectMake(50, line1.frame.origin.y+15, bgView.frame.size.width-100, 35)];
    self.pswField.secureTextEntry = YES;
    NSAttributedString *str1 = [[NSAttributedString alloc] initWithString:@"请输入密码" attributes:@{ NSForegroundColorAttributeName: [UIColor grayColor] }];
    self.pswField.attributedPlaceholder = str1;
    self.pswField.font = [UIFont systemFontOfSize:15];
    // 创建一个UIImageView来显示图标
    UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 18, 18)];
    UIImageView *iconImageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(-6, 0, 15, 15)];
    iconImageView2.image = [UIImage imageNamed:@"psw.png"];
    [view2 addSubview:iconImageView2];
//    145 × 128
    UIView *view3 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 18, 18)];
    UIButton *openButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [openButton setImage:[UIImage imageNamed:@"psw_open"] forState:0];
    [openButton setImage:[UIImage imageNamed:@"psw_close"] forState:UIControlStateSelected];
    openButton.frame = CGRectMake(0, 0, 23, 18);
    openButton.selected = true;
    [openButton addTarget:self action:@selector(pswOpen:) forControlEvents:UIControlEventTouchUpInside];
    [view3 addSubview:openButton];
    
    self.pswField.leftView = view2;
    self.pswField.rightView = view3;
    self.pswField.leftViewMode = UITextFieldViewModeAlways;
    self.pswField.rightViewMode = UITextFieldViewModeAlways;
    [bgView addSubview:self.pswField];
    
    //赋值
    if([dict count]){
        self.nameField.text = dict[@"username"];
        self.pswField.text = dict[@"password"];
    }
    
    UILabel *line2 = [[UILabel alloc] initWithFrame:CGRectMake(self.pswField.frame.origin.x, self.pswField.frame.origin.y+self.pswField.frame.size.height+10, self.nameField.frame.size.width, 1)];
    line2.backgroundColor = [UIColor lightGrayColor];
    line2.alpha = 0.1;
    [bgView addSubview:line2];
    
    //隐私协议
    UIButton *noteLabel = [[UIButton alloc] initWithFrame:CGRectMake(line2.frame.origin.x, line2.frame.origin.y+23, line2.frame.size.width, 20)];
    noteLabel.titleLabel.font = [UIFont systemFontOfSize:11];
    [noteLabel addTarget:self action:@selector(delegateAction) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:noteLabel];
    
   
    
    NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:@"登录即代表您同意《有因APP隐私协议》"];
    NSRange redRange = NSMakeRange([[noteStr string] rangeOfString:@"登录即代表您同意"].location, [[noteStr string] rangeOfString:@"登录即代表您同意"].length);
    [noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:redRange];

    NSRange greenRange = NSMakeRange([[noteStr string] rangeOfString:@"《有因APP隐私协议》"].location, [[noteStr string] rangeOfString:@"《有因APP隐私协议》"].length);
    [noteStr addAttribute:NSForegroundColorAttributeName value:rgba(25, 148, 255, 1) range:greenRange];
//    [noteLabel setAttributedText:noteStr];
    [noteLabel setAttributedTitle:noteStr forState:UIControlStateNormal];
    [noteLabel sizeToFit];
    
    
    //登录
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginBtn addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
    loginBtn.frame = CGRectMake(self.pswField.frame.origin.x, noteLabel.frame.origin.y+35, self.pswField.frame.size.width, 40);
    loginBtn.backgroundColor = rgba(25, 148, 255, 1);
    loginBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    loginBtn.layer.cornerRadius = 20;
    [bgView addSubview:loginBtn];
    
    //注册
//    UIButton *registerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [registerBtn addTarget:self action:@selector(registerAction) forControlEvents:UIControlEventTouchUpInside];
//    registerBtn.frame = CGRectMake(self.pswField.frame.origin.x, loginBtn.frame.origin.y+loginBtn.frame.size.height+15, self.pswField.frame.size.width, 20);
//    registerBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter;
//    registerBtn.titleLabel.font = [UIFont systemFontOfSize:15];
//    [registerBtn setTitle:@"暂无账号？立即注册" forState:UIControlStateNormal];
//    [registerBtn setTitleColor:rgba(25, 148, 255, 1) forState:UIControlStateNormal];
//    [bgView addSubview:registerBtn];
}

- (void)delegateAction
{
    WebViewController *webVC = [[WebViewController alloc] init];
    webVC.webUrl = @"https://xueyuan.youinsh.com/yinsixieyi.html";
    [self.navigationController pushViewController:webVC animated:YES];
}

- (void)registerAction
{
    WebViewController *webVC = [[WebViewController alloc] init];
    webVC.webUrl = @"https://m.youinsh.com/createFreeAccount.html?from=mobileLogin";
    [self.navigationController pushViewController:webVC animated:YES];
}
- (void)pswOpen:(UIButton *)sender
{
    sender.selected = !sender.selected;
    self.pswField.secureTextEntry = sender.selected;
}

#pragma mark - 登录
-(void)loginAction
{
    if(self.nameField.text.length<=0){
        [[ZXMessageCase shareInstace] showMessage:@"请输入登录账号"];
        return;
    }
    if(self.pswField.text.length<6){
        [[ZXMessageCase shareInstace] showMessage:@"请输入大于6位的密码"];
        return;
    }
    
    if ([self afn] == 0) {
        [[ZXMessageCase shareInstace] showMessage:@"当前网络不可用，请检查网络!"];
        return;
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 30.0f;
   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
    
    NSDictionary *params = @{@"username": self.nameField.text, @"password": self.pswField.text};
    NSString *urlString = [NSString stringWithFormat:@"%@v1/user/system/login/",HTTPSURL];
    __weak typeof(self) weakSelf = self;

    [manager POST:urlString parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if([responseObject[@"code"] intValue] == 200){
            
            NSString *token = responseObject[@"result"][@"tpzb_token"];
            
            //保存用户账号
            //username , password , exprise_time ,tpzb_token
            NSDictionary *userInfo = @{@"username": weakSelf.nameField.text, @"password": weakSelf.pswField.text,@"exprise_time":responseObject[@"result"][@"exprise_time"],@"token":token};
            
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:userInfo forKey:@"userInfo"];
            [defaults synchronize];
            
            [[YouinRTCManager shardManager] saveNSUserDefaults:@{@"token":token}];
            [YouinRTCManager shardManager].phone_pass_login_token = token;
            
            [[YouinRTCManager shardManager] getQiuNiuID:^(BOOL success, NSError * _Nullable error) {
            }];
            
            //跳转到直播列表
            LiveListViewController *listVC = [[LiveListViewController alloc] init];
            [weakSelf.navigationController pushViewController:listVC animated:YES];
        }else{
            UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:responseObject[@"msg"] preferredStyle:UIAlertControllerStyleAlert];
           
            UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
               
            }];
            [alertVc addAction:sureAction];
            [weakSelf presentViewController:alertVc animated:YES completion:nil];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
    }];
}


-(NSInteger)afn
{
   __block NSInteger afnStatus = 1; // -1 或者0 是无网络可用

    // 创建一个 Reachability 对象
    Reachability *reachability = [Reachability reachabilityForInternetConnection];

    // 开始监控网络状态
    [reachability startNotifier];

    // 获取网络状态
    NetworkStatus status = [reachability currentReachabilityStatus];

    switch (status) {
        case NotReachable:
            NSLog(@"无网络可用");
            afnStatus = 0;
            break;
        case ReachableViaWiFi:
            NSLog(@"当前连接 WiFi");
            afnStatus = 2;
            break;
        case ReachableViaWWAN:
            NSLog(@"当前连接 4G");
            afnStatus = 1;
            break;
        default:
            break;
    }
    
    return afnStatus;
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
